<template>
  <div class="manage-user">
    <el-menu-item index="12" @click="dialogVisible = !dialogVisible"> 用户管理 </el-menu-item>
    <el-dialog title="用户管理" v-model="dialogVisible" width="700" @closed="handleDialogClose">
      <div class="top">
        <el-button :icon="Plus" @click="showUserPopup('add')">添加用户</el-button>
        <!-- <user-popup v-model="userInfoVisible"></user-popup> -->
        <el-input v-model="search" placeholder="搜索用户" clearable></el-input>
      </div>
      <el-table :data="filteredData" height="400" stripe border highlight-current-row>
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column prop="username" label="用户名" width="150" sortable align="center" />
        <el-table-column prop="type" label="用户类型" width="110" sortable align="center">
          <template #default="{ row }">
            {{ convertType(row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="isOnline" label="登录状态" width="110" align="center">
          <template #default="{ row }">
            {{ getLoginStatus(row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <template v-if="row.type !== 'admin'">
              <el-button size="small" type="primary" @click="showUserPopup('edit', row)">
                修改
              </el-button>
              <el-button size="small" type="danger" @click="deleteUser(row.id)"> 注销 </el-button>
              <el-button
                size="small"
                type="warning"
                :disabled="!row.isOnline"
                @click="logout(row.id)"
              >
                下线
              </el-button>
            </template>
            <span v-else>--</span>
          </template>
        </el-table-column>
      </el-table>
      <user-popup
        v-model="userInfoVisible"
        :current-user="selectedUser"
        :mode="popupMode"
        @refresh="fetchUsers"
      ></user-popup>
    </el-dialog>
  </div>
</template>

<script setup>
import UserPopup from './UserPopup.vue'
import { ref, computed, onMounted, onUnmounted, defineExpose } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const dialogVisible = ref(false)
const userInfoVisible = ref(false)
const search = ref('')
const userData = ref([])
const popupMode = ref('add')
const selectedUser = ref(null)

// WebSocket 连接
const socket = new WebSocket('ws://localhost:8080')

// 心跳保持连接
const heartbeatInterval = setInterval(() => {
  if (socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify({ type: 'ping' }))
  }
}, 30000)

socket.addEventListener('message', (event) => {
  try {
    const message = JSON.parse(event.data)
    if (message.type === 'userUpdated') {
      fetchUsers() // 直接调用刷新方法
    }
  } catch (error) {
    console.error('消息解析失败:', error)
  }
})

// 获取用户数据
const fetchUsers = async () => {
  try {
    const { data } = await axios.post('http://localhost:3001/getuserbyname', { username: '' })
    // 检查后端返回的状态码
    if (data.data.status === 1) {
      const users = Array.isArray(data.data.data) ? data.data.data : [data.data.data]
      userData.value = users.map((user) => ({
        ...user,
        originalType: user.type,
      }))
    } else {
      console.error('未找到用户:', data.data.message)
    }
  } catch (error) {
    if (error.response) {
      console.error('请求错误:', error.response.data.error)
    } else {
      console.error('请求失败:', error.message)
    }
  }
}
onMounted(fetchUsers)

// 暴露 fetchUsers 方法
defineExpose({ fetchUsers })

// 带搜索功能的过滤、排序数据
const filteredData = computed(() => {
  return userData.value
    .filter((item) => item.username.includes(search.value))
    .sort(
      (a, b) =>
        (b.type === 'admin') - (a.type === 'admin') || // 管理员身份排序（admin在前）
        b.isOnline - a.isOnline, // 在线状态排序（true在前）
    )
})

const getLoginStatus = (row) => {
  return row.username === route.query.username ? '正在登录' : row.isOnline ? '在线' : '离线'
}

const convertType = (type) => {
  const typeMap = {
    admin: '管理员',
    traffic: '交通部门用户',
    common: '普通用户',
  }
  return typeMap[type]
}

const logout = async (id) => {
  ElMessageBox.confirm('确认让该用户下线？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const token = localStorage.getItem('token')
      axios
        .put(
          'http://localhost:3001/updateuser',
          {
            id,
            userObj: { isOnline: false },
          },
          { headers: { Authorization: `Bearer ${token}` } },
        )
        .then((updateRes) => {
          if (updateRes.status === 200) {
            ElMessage.success('下线成功')
            fetchUsers()
            // 发送 WebSocket 消息通知其他页面用户状态更新
            socket.send(
              JSON.stringify({
                type: 'userStatusUpdate',
                user: {
                  id: id,
                  isOnline: false,
                },
              }),
            )
          }
        })
        .catch((updateError) => {
          console.error('更新用户信息出错:', updateError)
          ElMessage.error('操作失败，请稍后重试')
        })
    })
    .catch(() => {
      ElMessage.info('已取消注销该用户')
    })
}

const deleteUser = async (id) => {
  ElMessageBox.confirm('确认删除该用户？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const token = localStorage.getItem('token')
      axios
        .post(
          'http://localhost:3001/deleteuser',
          { id },
          { headers: { Authorization: `Bearer ${token}` } },
        )
        .then((res) => {
          if (res.status === 204) {
            ElMessage.success('删除成功')
            fetchUsers()
            // 发送 WebSocket 消息通知其他页面用户状态更新
            socket.send(
              JSON.stringify({
                type: 'userStatusUpdate',
                user: {
                  id: id,
                  isOnline: false,
                },
              }),
            )
          }
        })
        .catch((error) => {
          console.error('删除用户失败:', error)
          ElMessage.error('操作失败，请稍后重试')
        })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

const showUserPopup = (mode, user = null) => {
  popupMode.value = mode
  selectedUser.value = user
  userInfoVisible.value = true
}

const handleDialogClose = () => {
  search.value = ''
}

// 关闭 WebSocket 连接
onUnmounted(() => {
  clearInterval(heartbeatInterval)
  socket.close()
})
</script>

<style lang="scss" scoped>
.manage-user {
  :deep(.top) {
    display: flex;
    justify-content: space-between;

    .el-input {
      width: 400px;
      margin-bottom: 20px;
    }
  }
  :deep(.el-table) {
    text-align: center;
  }

  :deep(.el-pagination) {
    margin-top: 10px;
    justify-content: center;
  }
}
</style>
